import jinja2
import os


jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

import cgi
import datetime
import urllib
import webapp2

from google.appengine.ext import db
from google.appengine.api import users
from django.utils import simplejson
 
from skinanonpython.pages import *
from skinanonpython.json import *

class GuestComments(db.Model):
    """Models an individual Guestbook entry with an author, content, and date."""
    author = db.StringProperty(multiline=False)
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)


def guestcomments_key(guestcomments_name=None):
    """Constructs a datastore key for a Guestbook entity with guestbook_name."""
    return db.Key.from_path('GuestComments', guestcomments_name or 'default_guestcomments')

        
class RPCHandler(webapp2.RequestHandler):
    """ Defines the methods that can be RPCed.
    NOTE: Do not allow remote callers access to private/protected "_*" methods.
    """
    def get(self):
        guestcomments_name=self.request.get('guestcomments_name')
        comment_query = GuestComments.all().ancestor(
            guestcomments_key(guestcomments_name)).order('-date')
        comments = comment_query.fetch(10)
        commentsJson  = encode(comments)
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'  
        self.response.out.write(commentsJson)
                                
class Guestbook(webapp2.RequestHandler):
    def post(self):
    # We set the same parent key on the 'Greeting' to ensure each greeting is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.
        guestcomments_name = self.request.get('guest_comments_name')
        comment = GuestComments(parent=guestcomments_key(guestcomments_name))

        comment.author = self.request.get('author')
        comment.content = self.request.get('content')
        comment.put()
        
        #self.redirect('/contactus?' + urllib.urlencode({'guest_comments_name': guestcomments_name}))
        self.redirect('/contactus')

app = webapp2.WSGIApplication([('/', AboutBook),
                               ('/aboutbook', AboutBook),
                               ('/aboutauthor', AboutAuthor),
                               ('/contactus', ContactUs),
                               ('/sign', Guestbook),
                               ('/comments',RPCHandler)],
                              debug=True)